<?php

    class NewsController extends Application {
        
        function setup()
        {
            $this->actions = array('index','modify','delete','categories','delete_category',
                                   'modify_category','search','browse_month','add_category','modify');
            $this->use_layout('admin_layout.php');
            $this->before_filter('is_logged_in');
            $this->before_filter('has_access');
            use_model('news','news_categories');
        }
        
        function has_access()
        {
            if (!has_access_to('News::Access News')) $this->redirect_to(array('controller'=>'admin/dashboard' ));
        }
        
		function index() 
		{
		    // list all news articles
		    $news = new News();		    
	        $this->assign('report',$news->get_paged_news());
	        $draft_list = $news->find(array(
	                                    'conditions'=>'status=0',
	                                    'fields'=>array('id','title')
	                                 ));
	        $this->assign('draft_list',$draft_list);
		}

		function browse_month()
		{
		    if ( !empty($_POST['date']['year']) 
		         && !empty($_POST['date']['mon']) )
		    {
		        $news = new News();
		        $this->assign('report',$news->browse_by_month( $_POST['date']['mon'],$_POST['date']['year'] ) );
		        $mdate  = get_month((int) $_POST['date']['mon']);
		        $ydate  = (int) $_POST['date']['year'];
		        $this->assign('search_date', "$mdate $ydate");
		    } else {
		        $this->redirect_to('index');
		    }
		}
        
        function modify()
        {            
            if ( !has_access_to('News::Add News') || !has_access_to('News::Edit News') )
            {
                $this->redirect_to('index');
            }
            
            $news = new News();
		    $this->assign_ref('news',$news);
		    $news_categories = new News_Categories();		    
		    $this->assign('all_categories',$news_categories->categories_as_list());
		    $go_back_to = isset($_GET['from_edit']) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : '';
		    $this->assign('go_back_to',$go_back_to);
		    // trying to modify by title
		    $id = '';
		    if ( isset($_POST['action']) && $_POST['action'] == 'find_by_title' )
		    {
		        // find the id by the title
		        $nid = $news->find(array(
		                            'search'=>'first',
		                            'conditions'=>array('title=?',$_POST['title']),
		                            'fields'=>'id'
		                            ));
		        if ( !empty($nid['id']) )
		        {
		            $id= $nid['id'];
		        } else {
		            flash('error','Post not found');
		            $this->redirect_to('index');
		        }
		    }
		    $id = !empty($_GET['id']) ? (int) $_GET['id'] : $id;
		    
		    if ( $id )
		    {
		        if ( $news->load( $id ) )
		        {
		            $this->assign('news_item',$news->fields);
		            $this->assign('news_item_categories', $news->selected_categories());
		        }
		    }
		    if ( $_POST )
		    {
		        if ( $_POST['news'] )
    		    {
    		        if ( isset($_POST['news']['id']) &&!has_access_to('News::Add News') ) {
    		            $this->redirect_to('index');
    		            return;
    		        } elseif (!isset($_POST['news']['id']) &&!has_access_to('News::Edit News')) {
    		            $this->redirect_to('index');
    		            return;
    		        }
    		        
    		        
    		        $news->load( (int) $_POST['news']['id']);
    		        
    		        // change timestamp?
    		        if ( isset($_POST['edit_timestamp']) )
    		        {
    		            $_POST['news']['publish_date'] = $_POST['date'];
    		        }
    		        
    		        if ( isset($_POST['commit']) && $_POST['commit'] == 'Publish')
    		        {
    		            $_POST['news']['status'] = 1; // publish it
    		        }
    		        
    		        if ( $news->update_fields($_POST['news']))
    	            {		            
    	                flash('notice','Post Saved');
    	                
    	                // ajax call
	                    if ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
                             $_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest' )
	                    {
	                        $script = "<div id='subautosave' style='padding:2px;margin:3px;display:table'>Post Autosaved</div>
                		    <script>new Effect.Highlight('subautosave',{duration: 3.0});
                		            setTimeout(\"new Effect.Fade('subautosave')\",1000);                		            
                		            $('news_id').value=".$news->get('id').";
                		            </script>";
                		    $this->render(array('inline'=>$script));
                		    return;
	                    }
    	                
    	                if ( isset($_POST['commit']) && $_POST['commit'] == 'Save and Continue Editing' )
    	                {    	                
    	                    $this->redirect_to(array('controller'=>'admin/news' ,'action'=>'modify?id='.$news->get('id')));     	                
         	            } elseif (!empty($_POST['go_back_to'])) {
         	                $this->redirect_to($_POST['go_back_to']);
    	                } else {
    	                    $this->redirect_to('index');   		               
    	                }
    	            } else {
    	                flash('error','Post failed to save');
    	            }
	            }
		    }
        }
        
        function delete()
        {
            if ( $_POST  && has_access_to('News::Delete News')) {
		        $news = new News();
		        $id = (int) $_POST['id'];
		        if ( $news->load($id) )
		        {
		            $news->delete();
		            flash('notice','Post Deleted');
		        }
		    }
		    $this->redirect_to('index');
        }
        
        function categories()
        {
            // list all categories
            $news_categories = new News_Categories();
            $this->assign('report',$news_categories->get_paged_categories());
            $default_category = $news_categories->find(
                                                        array(
                                                            'search'=>'first',
                                                            'conditions'=>'id=1',
                                                            'fields'=>'name'
                                                            )
                                                      );
            
            $this->assign('default_category',$default_category['name']);
        }
        
        function modify_category()
        {
            if(!has_access_to('News::Manage News Categories')) {
                $this->redirect_to('index');
                return;
            }
            $news_categories = new News_Categories();
            $this->assign_ref('category',$news_categories);
            $this->assign('all_categories',$news_categories->categories_as_list());
            if ( !empty($_GET['id']) )
            {
                $id = (int) $_GET['id'];
                $news_categories->load($id);
                $this->assign('cat',$news_categories->fields);
            }
            if ( !empty($_POST['category']) )
            {
                $id = $_POST['category']['id'];
                $news_categories->load($id);
                if ( $news_categories->update_fields($_POST['category']) )
                {
                    flash('notice','Category Saved');
                    $this->redirect_to('categories');
                } else {
                    $this->assign('cat',true);
                    flash('error','Category could not be saved');
                }
            }
        }        
        
        function add_category()
        {
            if(!has_access_to('News::Manage News Categories')) {
                $this->redirect_to('index');
                return;
            }
            if ( !empty($_POST['new_category']) )
            {
                $news_categories = new News_Categories();
                $news_categories->set('name',$_POST['new_category']);
                if ( $news_categories->save() )
                {
                    $this->assign('id',$news_categories->get('id'));
                    $this->assign('name',$news_categories->get('name'));
                    $this->render(array('partial'=>'_new_category.php'));
                } else {
                    $errors  = implode('<br>',$news_categories->get_errors_on('name'));
                    $emsg    = "<script>alert('".escape_javascript($errors)."')</script>";
                    $this->render(array('inline'=>$emsg));
                }
            }
        }
        
        function delete_category()
        {
            if(!has_access_to('News::Manage News Categories')) {
                $this->redirect_to('index');
                return;
            }
            if ( isset($_POST['id']) )
            {
                $news_categories = new News_Categories();            
                if ( $news_categories->load( (int) $_POST['id']) )
                {
                    $news_categories->delete();
                    flash('notice','Category deleted');
                }
            }
            $this->redirect_to('categories');
        }
        
        function search()
        {
            if ( $_POST )
            {
                $news = new News();
    		    $found_news = $news->find( array(
    		                                'conditions'=>array('lower(title) like ?', '%'.strtolower($_POST['title']).'%'),
    		                                'order' =>'title asc',
    		                                'limit'=>8,
    		                                'fields'=>'title'
    		                                ) );

    		    $this->assign('found_news',$found_news);
    		    $this->render(array('partial'=>'_found_news.php'));
            }
        }
        
    }

?>